#include "btree.h"
#include "esbtree.h"
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <time.h>
#include <cstring>
using namespace std;

int main()
{
	
	bt_tree * btree;
	esbt_tree * esbtree;
	
	btree = btree_create(ORDER);
	esbtree = esbtree_create(ORDER);

	bt_entry ** kv;
	
	ifstream fconfig;
	fconfig.open("config.ini");
	char treetype[4], datafile[128];
	fconfig.getline((char *)treetype, 4);
	fconfig.getline((char *)datafile, 128);
	fconfig.close();

	ifstream fin;
	fin.open(datafile);
	int count;
	int value;
	fin >> count;
	int *keys = new int[count];
	for (unsigned i = 0; i < count; i++)
	{
		fin >> value;
		keys[i] = value;
	}

	fin.close();

	kv = (bt_entry **)malloc(count * sizeof(bt_entry *));

	for (unsigned i = 0; i < count; i++) 
	{	
		bt_entry * entry = (bt_entry*)malloc(sizeof(bt_entry));
		entry->key = (int *)keys[i];
		kv[i] = entry;
	}

	clock_t start, end;

	cout << count << endl;

	if (treetype[0] == '0') 
	{
		start = clock();

		for(unsigned i = 0; i < count; i++)
		{
			btree_insert(btree, kv[i]);
		}

		end = clock();

		cout << "btree insert time:"<< end << " - " << start << " = " << end  - start << endl;

		bt_entry * result = (bt_entry *)malloc(sizeof(bt_entry));

		start = clock();
		int num = 0;

		for(int i = 0; i < count; i++)
		{
			btree_search(btree, kv[i], result);
 			if (kv[i]->key != result->key)
			{
				num++;
			}
		}

		end = clock();

		cout << "wrong:" << num << endl;

		cout << "btree search time:"<< end << " - " << start << " = " << end  - start << endl;
	}
	else if(treetype[0] == '1')
	{
		start = clock();

		for(unsigned i = 0; i < count; i++)
		{
			esbtree_insert(esbtree, kv[i]);
		}

		end = clock();

		cout << "esbtree insert time:"<< end << " - " << start << " = " << end  - start << endl;

		bt_entry * result = (bt_entry *)malloc(sizeof(bt_entry));

		start = clock();
		int num = 0;

		for(int i = 0; i < count; i++)
		{
			esbtree_search(esbtree, kv[i], result);
 			if (kv[i]->key != result->key)
			{
				num++;
			}
		}

		end = clock();

		cout << "wrong:" << num << endl;

		cout << "esbtree search time:"<< end << " - " << start << " = " << end  - start << endl;
	}

	cout << "Hello World!" << endl;

	return 0;
}
